package com.hq.autotesttools;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.TextView;

import java.util.UUID;

public class DeviceControlActivity extends AppCompatActivity {
    private String TAG = "DeviceControl";

    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    private String mDeviceName;
    private String mDeviceAddress;

    private TextView mDeviceNameView;
    private TextView mDeviceMacView;

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothGatt mBluetoothGatt;

    private static final UUID GENERIC_ATTRIBUTE_UUID = UUID.fromString("00001801-0000-1000-8000-00805f9b34fb");
    private static final UUID GENERIC_ACCESS_UUID = UUID.fromString("00001800-0000-1000-8000-00805f9b34fb");

    private static final UUID DEVICE_NAME_UUID = UUID.fromString("00002a00-0000-1000-8000-00805f9b34fb");
    private static final UUID APPEARANCE_UUID = UUID.fromString("00002a01-0000-1000-8000-00805f9b34fb");

    private static final UUID UNKNOW_SERVICE_UUID = UUID.fromString("000000ff-0000-1000-8000-00805f9b34fb");
    private static final UUID UNKNOW_SERVICE_CHARACTERISTIC_1_UUID = UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb");
    private static final UUID UNKNOW_SERVICE_CHARACTERISTIC_2_UUID = UUID.fromString("0000ff02-0000-1000-8000-00805f9b34fb");
    private static final UUID UNKNOW_SERVICE_CHARACTERISTIC_3_UUID = UUID.fromString("0000ff03-0000-1000-8000-00805f9b34fb");

    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            Log.d(TAG, "onConnectionStateChange: " + newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                if (gatt.discoverServices()) {
                    Log.d(TAG, "onConnectionStateChange: Service discover Start");
                }
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            String name1 = null;
            super.onCharacteristicRead(gatt, characteristic, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "onCharacteristicRead: success");
//                name1 = characteristic.getStringValue(0);
//                if (name1 != null && name1.length() > 0) {
//                    Log.d(TAG, "onCharacteristicRead read finished: " + name1);
//                }

                final byte[] data = characteristic.getValue();
                if (data != null && data.length > 0) {
                    final StringBuilder stringBuilder = new StringBuilder(data.length);
                    for (byte byteChar : data)
                        stringBuilder.append(String.format("%02X ", byteChar));

                    Log.d(TAG, "onCharacteristicRead: " + new String(data) + "\t" +
                            stringBuilder.toString());
                }
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);

            Log.d(TAG, "onCharacteristicChanged: zxy");

        }

        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            super.onReadRemoteRssi(gatt, rssi, status);
            Log.d(TAG, "onReadRemoteRssi: rssi " + rssi);

        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            UUID mUUID = null;
            super.onServicesDiscovered(gatt, status);
//            List<BluetoothGattService> ListGattService = gatt.getServices();
//            if (ListGattService != null) {
//                for (BluetoothGattService gattService : ListGattService) {
//                    mUUID = gattService.getUuid();
//                    Log.d(TAG, "onServicesDiscovered: " + mUUID.toString());
//                }
//            }

            Log.d(TAG, "onServicesDiscovered: get Service");
            BluetoothGattService mService = mBluetoothGatt.getService(GENERIC_ACCESS_UUID);
            BluetoothGattCharacteristic mCharacteristic = mService.getCharacteristic(DEVICE_NAME_UUID);
            Log.d(TAG, "onServicesDiscovered: properties 1 " + mCharacteristic.getProperties());

            if (ActivityCompat.checkSelfPermission(DeviceControlActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            mBluetoothGatt.readCharacteristic(mCharacteristic);

//            String name1 = null;
//            for (int count = 20; count > 0; count--) {
//                Log.d(TAG, "onServicesDiscovered: " + count);
//                name1 = mCharacteristic.getStringValue(30);
//                if (name1 != null && name1.length() > 0) {
//                    Log.d(TAG, "onServicesDiscovered: " + name1);
//                }
//            }
//            byte[] name = mCharacteristic.getValue();
//            int count = 3;
//            do {
//                count--;
//                Log.d(TAG, "onServicesDiscovered: " + count + " read");
//                if (name != null && name.length > 0) {
//                    final StringBuilder stringBuilder = new StringBuilder(name.length);
//                    for (byte byteChar : name) {
//                        stringBuilder.append(String.format("%02X", byteChar));
//                    }
//                    Log.d(TAG, "onServicesDiscovered: " + stringBuilder.toString());
//                } else {
//                    name = mCharacteristic.getValue();
//                }
//            } while (count != 0);
        }
    };


    @SuppressLint("MissingPermission")
    private void Connect(String DeviceAddress) {
        try {
            final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(DeviceAddress);
            mBluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback);
        } catch (IllegalArgumentException exception) {
            Log.w(TAG, "Device not found with provided address." + exception);
//                return false;
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_control);

        // Keep Screen on.
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

        mDeviceNameView = findViewById(R.id.DeviceName);
        mDeviceMacView = findViewById(R.id.DeviceMac);

        mDeviceNameView.setText(mDeviceName.toString());
        mDeviceMacView.setText(mDeviceAddress.toString());

        Connect(mDeviceAddress);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mBluetoothGatt.disconnect();
        Log.d(TAG, "onPause: ");
    }
}